package com.ys.service.storage.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.entity.storage.TccLogisticsChannelDetail;
import com.ys.entity.storage.TccLogisticsComprehensive;
import com.ys.enume.storage.TccFbaLogisticsMethodEnum;
import com.ys.enume.storage.TccLogisticsComprehensiveEnum;
import com.ys.mapper.storage.StorageMapper;
import com.ys.mapper.storage.TccLogisticsComprehensiveMapper;
import com.ys.service.storage.TccLogisticsApiService;
import com.ys.service.storage.TccLogisticsReconcileService;
import com.ys.util.CheckUtil;
import com.ys.vo.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * @Author: fxz
 * @CreateTime: 2025-03-04
 * @Description: 物流对账单实现类
 * @Version: 1.0
 */
@Service("tccLogisticsReconcileService")
public class TccLogisticsReconcileServiceImpl implements TccLogisticsReconcileService {

    @Autowired
    private CheckUtil checkUtil;

    private static final Logger logger = LoggerFactory.getLogger(TccLogisticsReconcileServiceImpl.class);


    @Autowired
    private TccLogisticsComprehensiveMapper tccLogisticsComprehensiveMapper;

    @Autowired
    private StorageMapper storageMapper;

    @Autowired
    private TccLogisticsApiService tccLogisticsApiService;

    //服务商物流费用导入
    @Override
    public R costImport(String rows, Long menuId) throws Exception{
        logger.info("服务商物流费用导入的数据：\n" + rows);

        JSONArray detailList = JSON.parseArray(rows);
        StringBuilder errorMsg = new StringBuilder();
        for(int i=0;i<detailList.size();i++) {
            JSONObject info = detailList.getJSONObject(i);
            Map infoMap = JSONObject.parseObject(info.toString(), Map.class);
            //验证导入字段

            if (checkUtil.isNullByObject(infoMap.get("fbaNo"))) {
                return R.error("FBA编号为空");
            }

            if (checkUtil.isNullByObject(infoMap.get("spOrderBid"))) {
                return R.error("服务商订单号为空");
            }

            if (checkUtil.isNullByObject(infoMap.get("spLogsticsFee"))) {
                return R.error("服务商物流费用(导入)为空");
            }

            List<TccLogisticsComprehensive> logisticsComprehensiveList = new TccLogisticsComprehensive()
                    .where("A.FbaNo = '"+infoMap.get("fbaNo").toString()+"'")
                    .queryList();

            if(logisticsComprehensiveList!=null && logisticsComprehensiveList.size()>0){
                for(TccLogisticsComprehensive tccLogisticsComprehensive:logisticsComprehensiveList){
                    if(tccLogisticsComprehensive.getLogPayStatusZf().equals(TccLogisticsComprehensiveEnum.LogPayStatusZf.COMPLETE.value)){
                        errorMsg.append("第"+(i+1)+"条数据，FBA编号:"+info.get("fbaNo") + "的数据物流付款状态已完整,不可再导入!");
                        continue;
                    }
                    //服务商订单号
                    tccLogisticsComprehensive.setSpOrderBid(infoMap.get("spOrderBid").toString());
                    //服务商物流费用
                    tccLogisticsComprehensive.setSpLogsticsFee(new BigDecimal(infoMap.get("spLogsticsFee").toString()));
                    //物流订单利润（对账） = 物流发票费用（总）-服务商物流费用（导入）
                    tccLogisticsComprehensive.setLogOrderProfitDz(tccLogisticsComprehensive.getLogInvoiceCost().subtract(tccLogisticsComprehensive.getSpLogsticsFee()));
                    //物流服务利润（对账） = 物流销售费用（总）-服务商物流费用（导入）
                    tccLogisticsComprehensive.setLogServiceProfitDz(tccLogisticsComprehensive.getLogInvoiceSalesFee().subtract(tccLogisticsComprehensive.getSpLogsticsFee()));
                    //物流订单利润率（对账） = 物流订单利润（对账）/服务商物流费用（导入）*100%
                    tccLogisticsComprehensive.setLogOrderMarginDz(
                            (tccLogisticsComprehensive.getLogOrderProfitDz().divide(tccLogisticsComprehensive.getSpLogsticsFee(),2,BigDecimal.ROUND_HALF_UP))
                            .multiply(new BigDecimal(100))
                    );
                    //物流服务利润率（对账） = 物流服务利润（对账）/服务商物流费用（导入）*100%
                    tccLogisticsComprehensive.setLogServiceMarginDz(
                            (tccLogisticsComprehensive.getLogServiceProfitDz().divide(tccLogisticsComprehensive.getSpLogsticsFee(),2,BigDecimal.ROUND_HALF_UP))
                                    .multiply(new BigDecimal(100))
                    );
                    //物流订单对账状态 物流订单利润率（对账）≥0 盈利 |物流订单利润率（对账）＜0 低利润|物流服务利润率（对账）＜0 亏损
                    int logOrderStatusDz = 0;
                    if (tccLogisticsComprehensive.getLogOrderMarginDz().compareTo(BigDecimal.ZERO) >= 0){
                        logOrderStatusDz = TccLogisticsComprehensiveEnum.LogOrderStatusDz.PROFIT.value;
                    }else if (tccLogisticsComprehensive.getLogServiceMarginDz().compareTo(BigDecimal.ZERO) < 0){
                        logOrderStatusDz = TccLogisticsComprehensiveEnum.LogOrderStatusDz.DEFICIT.value;
                    }else {
                        logOrderStatusDz = TccLogisticsComprehensiveEnum.LogOrderStatusDz.LOWPROFIT.value;
                    }
                    tccLogisticsComprehensive.setLogOrderStatusDz(logOrderStatusDz);
                    //设置状态
                    tccLogisticsComprehensive = setStatus(tccLogisticsComprehensive);
                    tccLogisticsComprehensiveMapper.update(tccLogisticsComprehensive);
                }
            }else {
                errorMsg.append("第"+(i+1)+"条数据，FBA编号:"+info.get("fbaNo") + "的数据不存在!");
                continue;
            }
        }
        if(errorMsg.length()>0){
            return R.ok(errorMsg.toString());
        }
        return R.ok("导入成功");
    }

    /**
     * 服务商关税费用导入
     * @param rows
     * @param menuId
     * @return
     * @throws Exception
     */
    @Override
    public R gsImport(String rows, Long menuId) throws Exception {
        logger.info("服务商关税费用导入的数据：\n" + rows);

        JSONArray detailList = JSON.parseArray(rows);
        StringBuilder errorMsg = new StringBuilder();
        for(int i=0;i<detailList.size();i++) {
            JSONObject info = detailList.getJSONObject(i);
            Map infoMap = JSONObject.parseObject(info.toString(), Map.class);
            //验证导入字段

            if (checkUtil.isNullByObject(infoMap.get("fbaNo"))) {
                return R.error("FBA编号为空");
            }

            if (checkUtil.isNullByObject(infoMap.get("serviceTariff"))) {
                return R.error("服务商关税费用(导入)为空");
            }

            List<TccLogisticsComprehensive> logisticsComprehensiveList = new TccLogisticsComprehensive()
                    .where("A.FbaNo = '"+infoMap.get("fbaNo").toString()+"'")
                    .queryList();

            if(logisticsComprehensiveList!=null && logisticsComprehensiveList.size()>0){
                for(TccLogisticsComprehensive tccLogisticsComprehensive:logisticsComprehensiveList){
                    if(tccLogisticsComprehensive.getTariffPayStatus().equals(TccLogisticsComprehensiveEnum.TariffPayStatus.COMPLETE.value)){
                        errorMsg.append("第"+(i+1)+"条数据，FBA编号:"+info.get("fbaNo") + "的数据关税付款状态已完整,不可再导入!");
                        continue;
                    }
                    //服务商关税费用（导入）
                    tccLogisticsComprehensive.setServiceTariff(new BigDecimal(infoMap.get("serviceTariff").toString()));
                    //FBA的商品采购价*商品数量之和
                    BigDecimal purchaseAmountSum = storageMapper.countPurchaseAmountSum(tccLogisticsComprehensive.getFbaDeliverItemId());
                    //关税利率 = 服务商关税费用/（FBA的商品采购价*商品数量之和）
                    tccLogisticsComprehensive.setRateDuty(
                            (tccLogisticsComprehensive.getServiceTariff().divide(purchaseAmountSum,2,BigDecimal.ROUND_HALF_UP))
                                    .multiply(new BigDecimal(100)));
                    //设置状态
                    tccLogisticsComprehensive = setStatus(tccLogisticsComprehensive);
                    tccLogisticsComprehensiveMapper.update(tccLogisticsComprehensive);
                }
            }else {
                errorMsg.append("第"+(i+1)+"条数据，FBA编号:"+info.get("fbaNo") + "的数据不存在!");
                continue;
            }
        }
        if(errorMsg.length()>0){
            return R.ok(errorMsg.toString());
        }
        return R.ok("导入成功");
    }

    /**
     * 对账说明导入
     * @param rows
     * @param menuId
     * @return
     * @throws Exception
     */
    @Override
    public R dZsmImport(String rows, Long menuId) throws Exception {
        logger.info("对账说明导入的数据：\n" + rows);

        JSONArray detailList = JSON.parseArray(rows);
        StringBuilder errorMsg = new StringBuilder();
        for(int i=0;i<detailList.size();i++) {
            JSONObject info = detailList.getJSONObject(i);
            Map infoMap = JSONObject.parseObject(info.toString(), Map.class);
            //验证导入字段

            if (checkUtil.isNullByObject(infoMap.get("fbaNo"))) {
                return R.error("FBA编号为空");
            }

            if (checkUtil.isNullByObject(infoMap.get("logOrderlDesDz"))) {
                return R.error("物流订单对账说明为空");
            }

            List<TccLogisticsComprehensive> logisticsComprehensiveList = new TccLogisticsComprehensive()
                    .where("A.FbaNo = '"+infoMap.get("fbaNo").toString()+"'")
                    .queryList();

            if(logisticsComprehensiveList!=null && logisticsComprehensiveList.size()>0){
                for(TccLogisticsComprehensive tccLogisticsComprehensive:logisticsComprehensiveList){
                    if(tccLogisticsComprehensive.getLogPayStatusZf().equals(TccLogisticsComprehensiveEnum.LogPayStatusZf.COMPLETE.value)){
                        errorMsg.append("第"+(i+1)+"条数据，FBA编号:"+info.get("fbaNo") + "的数据物流付款状态已完整,不可再导入!");
                        continue;
                    }
                    //物流订单对账说明
                    tccLogisticsComprehensive.setLogOrderlDesDz(infoMap.get("logOrderlDesDz").toString());
                    tccLogisticsComprehensiveMapper.update(tccLogisticsComprehensive);
                }
            }else {
                errorMsg.append("第"+(i+1)+"条数据，FBA编号:"+info.get("fbaNo") + "的数据不存在!");
                continue;
            }
        }
        if(errorMsg.length()>0){
            return R.ok(errorMsg.toString());
        }
        return R.ok("导入成功");
    }

    /**
     * api对账
     * @param params
     * @return
     */
    @Override
    public R apiDz(Map<String, Object> params) {
        if (params == null){
            return R.error("选择数据不允许为空!");
        }
        if (params.get("list") == null) {
            return R.error("选择数据不能为空!");
        }
        String[] strs = params.get("list").toString().split(",");
        Set<String> idList = new HashSet<>();
        for(String bid : strs){
            idList.add(bid);
        }
        for (String bid :idList){
            List<TccLogisticsComprehensive> logisticsComprehensiveList = new TccLogisticsComprehensive().setLogInvoiceNo(bid)
                    .where("A.Status != 0")
                    .queryList();
            if (logisticsComprehensiveList.size() == 0){
                continue;
            }

            //物流对账信息
            TccLogisticsComprehensive tccLogisticsComprehensive = logisticsComprehensiveList.get(0);

            //获取费用api
            R r = tccLogisticsApiService.getPrice(tccLogisticsComprehensive);
            if (r.getCode() == R.Code.FAILED.value) {
                if (r.getMsg().equals("该物流服务商，无法api下单，请知晓。")){
                    continue;
                }else {
                    return r;
                }
            }

            //处理费用
            JSONObject getData = JSONObject.parseObject(r.get("data").toString());
            JSONObject data = JSONObject.parseObject(getData.get("data").toString());
            if (!data.get("orderno").toString().equals(tccLogisticsComprehensive.getSpOrderBid())){
                return R.error("获取的数据不匹配,请核实后再操作!");
            }
            //关税
            BigDecimal serviceTariff = BigDecimal.ZERO;
            //物流
            BigDecimal spLogsticsFee = BigDecimal.ZERO;

            JSONArray details = JSONArray.parseArray(data.get("details").toString());
            if(details!=null && details.size()>0){
                for(int i=0;i<details.size();i++){
                    JSONObject jsonObjectData = (JSONObject)details.get(i);
                    if (jsonObjectData.get("chargenm").equals("关税")){
                        serviceTariff = serviceTariff.add(new BigDecimal(jsonObjectData.get("amt").toString()));
                    }else {
                        spLogsticsFee = spLogsticsFee.add(new BigDecimal(jsonObjectData.get("amt").toString()));
                    }
                }
            }


            //物流动作
            if (spLogsticsFee.compareTo(BigDecimal.ZERO) > 0){
                if(logisticsComprehensiveList!=null && logisticsComprehensiveList.size()>0){
                    for(TccLogisticsComprehensive tccLogisticsComprehensiveNew:logisticsComprehensiveList){
                        if(tccLogisticsComprehensiveNew.getLogPayStatusZf().equals(TccLogisticsComprehensiveEnum.LogPayStatusZf.COMPLETE.value)){
                            continue;
                        }
                        //服务商物流费用
                        tccLogisticsComprehensiveNew.setSpLogsticsFee(spLogsticsFee);
                        //物流订单利润（对账） = 物流发票费用（总）-服务商物流费用（导入）
                        tccLogisticsComprehensiveNew.setLogOrderProfitDz(tccLogisticsComprehensiveNew.getLogInvoiceCost().subtract(tccLogisticsComprehensiveNew.getSpLogsticsFee()));
                        //物流服务利润（对账） = 物流销售费用（总）-服务商物流费用（导入）
                        tccLogisticsComprehensiveNew.setLogServiceProfitDz(tccLogisticsComprehensiveNew.getLogInvoiceSalesFee().subtract(tccLogisticsComprehensiveNew.getSpLogsticsFee()));
                        //物流订单利润率（对账） = 物流订单利润（对账）/服务商物流费用（导入）*100%
                        tccLogisticsComprehensiveNew.setLogOrderMarginDz(
                                (tccLogisticsComprehensiveNew.getLogOrderProfitDz().divide(tccLogisticsComprehensiveNew.getSpLogsticsFee(),2,BigDecimal.ROUND_HALF_UP))
                                        .multiply(new BigDecimal(100))
                        );
                        //物流服务利润率（对账） = 物流服务利润（对账）/服务商物流费用（导入）*100%
                        tccLogisticsComprehensiveNew.setLogServiceMarginDz(
                                (tccLogisticsComprehensiveNew.getLogServiceProfitDz().divide(tccLogisticsComprehensiveNew.getSpLogsticsFee(),2,BigDecimal.ROUND_HALF_UP))
                                        .multiply(new BigDecimal(100))
                        );
                        //物流订单对账状态 物流订单利润率（对账）≥0 盈利 |物流订单利润率（对账）＜0 低利润|物流服务利润率（对账）＜0 亏损
                        int logOrderStatusDz = 0;
                        if (tccLogisticsComprehensiveNew.getLogOrderMarginDz().compareTo(BigDecimal.ZERO) >= 0){
                            logOrderStatusDz = TccLogisticsComprehensiveEnum.LogOrderStatusDz.PROFIT.value;
                        }else if (tccLogisticsComprehensiveNew.getLogServiceMarginDz().compareTo(BigDecimal.ZERO) < 0){
                            logOrderStatusDz = TccLogisticsComprehensiveEnum.LogOrderStatusDz.DEFICIT.value;
                        }else {
                            logOrderStatusDz = TccLogisticsComprehensiveEnum.LogOrderStatusDz.LOWPROFIT.value;
                        }
                        tccLogisticsComprehensiveNew.setLogOrderStatusDz(logOrderStatusDz);
                        //设置状态
                        tccLogisticsComprehensiveNew = setStatus(tccLogisticsComprehensiveNew);
                        tccLogisticsComprehensiveMapper.update(tccLogisticsComprehensiveNew);
                    }
                }
            }

            //关税动作
            if (serviceTariff.compareTo(BigDecimal.ZERO) > 0) {
                if (logisticsComprehensiveList != null && logisticsComprehensiveList.size() > 0) {
                    for (TccLogisticsComprehensive tccLogisticsComprehensiveNew : logisticsComprehensiveList) {
                        if (tccLogisticsComprehensiveNew.getTariffPayStatus().equals(TccLogisticsComprehensiveEnum.TariffPayStatus.COMPLETE.value)) {
                            continue;
                        }
                        //服务商关税费用（导入）
                        tccLogisticsComprehensiveNew.setServiceTariff(serviceTariff);
                        //FBA的商品采购价*商品数量之和
                        BigDecimal purchaseAmountSum = storageMapper.countPurchaseAmountSum(tccLogisticsComprehensiveNew.getFbaDeliverItemId());
                        //关税利率 = 服务商关税费用/（FBA的商品采购价*商品数量之和）
                        tccLogisticsComprehensiveNew.setRateDuty(
                                (tccLogisticsComprehensiveNew.getServiceTariff().divide(purchaseAmountSum, 2, BigDecimal.ROUND_HALF_UP))
                                        .multiply(new BigDecimal(100)));
                        //设置状态
                        tccLogisticsComprehensiveNew = setStatus(tccLogisticsComprehensiveNew);
                        tccLogisticsComprehensiveMapper.update(tccLogisticsComprehensiveNew);
                    }
                }
            }
        }
        return R.ok("api对账成功!");
    }

    private TccLogisticsComprehensive setStatus(TccLogisticsComprehensive tccLogisticsComprehensive){
        //查询物流渠道信息
        TccLogisticsChannelDetail tccLogisticsChannelDetail = new TccLogisticsChannelDetail().setBid(tccLogisticsComprehensive.getLogOrderBid()).queryFirst();
        if (tccLogisticsComprehensive.getSpLogsticsFee().compareTo(BigDecimal.ZERO) != 0){
            //服务商物流费用（导入）≠0 或者自税 服务商关税费用（导入）=0  =>物流订单待关税
            //清关方式（0自税、1包税 ,2包税单发---拼票标记）
            if (tccLogisticsChannelDetail.getNameLogsticsClearance() == TccFbaLogisticsMethodEnum.NameLogsticsClearance.SELFTAX.value){
                //包税 服务商关税费用（导入）≠0  物流订单已对账
                if (tccLogisticsComprehensive.getServiceTariff().compareTo(BigDecimal.ZERO) != 0){
                    tccLogisticsComprehensive.setTariffZfStatus(TccLogisticsComprehensiveEnum.TariffZfStatus.COMPLETE.value);
                    tccLogisticsComprehensive.setStatus(TccLogisticsComprehensiveEnum.Status.ISRECONCILIATION.value);
                }
            }else {
                //包税直接就是已对账
                tccLogisticsComprehensive.setStatus(TccLogisticsComprehensiveEnum.Status.ISRECONCILIATION.value);
            }
        }

        return tccLogisticsComprehensive;
    }
}
